import backtrader as bt
from backtrader.brokers import BackBroker


class ForexSpreadCommissionScheme(bt.CommInfoBase):
    '''
    This commission scheme attempts to calcuate the commission hidden in the
    spread by most forex brokers. It assumes a mid point data is being used.

    *New Params*
    spread: Float, the spread in pips of the instrument
    JPY_pair: Bool, states whether the pair being traded is a JPY pair
    acc_counter_currency: Bool, states whether the account currency is the same
    as the counter currency. If false, it is assumed to be the base currency
    '''

    params = (
        ('spread', 2.0),
        ('stocklike', False),
        ('jpy_pair', False),
        ('acc_counter_currency', True),
        ('commtype', bt.CommInfoBase.COMM_FIXED),
    )

    def _getcommission(self, size, price, pseudoexec):
        '''
        This scheme will apply half the commission when buying and half when selling.
        For JPY pairs the multiplier is changed accordingly.
        If account currency is same as the base currency, change pip value calc.
        '''
        if self.p.jpy_pair == True:
            multiplier = 0.0001
        else:
            multiplier = 0.000001

        if self.p.acc_counter_currency == True:
            comm = abs((self.p.spread * (size * multiplier) / 2))

        else:
            comm = abs((self.p.spread * ((size / price) * multiplier) / 2))
        return comm

    # def getvaluesize(self, opened, price):
    #     return abs(opened)

    def getsize(self, price, cash):
        return cash



class ForexBroker(BackBroker):
    pass
